﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MvCamCtrl.NET;
using MvCamCtrl.NET.CameraParams;
using System.Runtime.InteropServices;
using System.Threading;
using System.IO;

using System.Drawing.Imaging;
using System.Diagnostics;
using System.Collections.ObjectModel;

namespace BasicDemoLineScan
{
    public partial class Form1 : Form
    {
        private CCamera m_MyCamera = new CCamera();
        List<CCameraInfo> m_ltDeviceList = new List<CCameraInfo>();

        bool m_bGrabbing = false;
        Thread m_hReceiveThread = null;

        // ch:用于从驱动获取图像的缓存 | en:Buffer for getting image from driver
        private static Object BufForDriverLock = new Object();
        CImage m_pcImgForDriver;          // 图像信息
        CFrameSpecInfo m_pcImgSpecInfo;   // 图像的水印信息

        // ch:Bitmap | en:Bitmap
        Bitmap m_pcBitmap = null;
        PixelFormat m_enBitmapPixelFormat = PixelFormat.DontCare;
        MV_CAM_TRIGGER_MODE m_enTriggerMode = MV_CAM_TRIGGER_MODE.MV_TRIGGER_MODE_OFF;
        MV_CAM_TRIGGER_SOURCE m_enTriggerSource = MV_CAM_TRIGGER_SOURCE.MV_TRIGGER_SOURCE_LINE0;

        CEnumValue m_pcTriggerSelector = new CEnumValue();  // 触发选项
        CEnumValue m_pcTriggerMode = new CEnumValue();      // 触发模式
        CEnumValue m_pcTriggerSource = new CEnumValue();    // 触发源
        CEnumValue m_pcPixelFormat = new CEnumValue();      // 像素格式
        CEnumValue m_pcImgCompressMode = new CEnumValue();  // HB模式
        CEnumValue m_pcPreampGain = new CEnumValue();       // 模拟增益

        public Form1()
        {
            InitializeComponent();
            DeviceListAcq();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        /// <summary>
        /// // ch:显示错误信息 | en:Show error message
        /// </summary>
        /// <param name="csMessage">ch:错误信息 | en: error message</param>
        /// <param name="nErrorNum">ch:错误码 | en: error code</param>
        private void ShowErrorMsg(string csMessage, int nErrorNum)
        {
            string errorMsg;
            if (nErrorNum == 0)
            {
                errorMsg = csMessage;
            }
            else
            {
                errorMsg = csMessage + ": Error =" + String.Format("{0:X}", nErrorNum);
            }

            switch (nErrorNum)
            {
                case CErrorDefine.MV_E_HANDLE: errorMsg += " Error or invalid handle "; break;
                case CErrorDefine.MV_E_SUPPORT: errorMsg += " Not supported function "; break;
                case CErrorDefine.MV_E_BUFOVER: errorMsg += " Cache is full "; break;
                case CErrorDefine.MV_E_CALLORDER: errorMsg += " Function calling order error "; break;
                case CErrorDefine.MV_E_PARAMETER: errorMsg += " Incorrect parameter "; break;
                case CErrorDefine.MV_E_RESOURCE: errorMsg += " Applying resource failed "; break;
                case CErrorDefine.MV_E_NODATA: errorMsg += " No data "; break;
                case CErrorDefine.MV_E_PRECONDITION: errorMsg += " Precondition error, or running environment changed "; break;
                case CErrorDefine.MV_E_VERSION: errorMsg += " Version mismatches "; break;
                case CErrorDefine.MV_E_NOENOUGH_BUF: errorMsg += " Insufficient memory "; break;
                case CErrorDefine.MV_E_UNKNOW: errorMsg += " Unknown error "; break;
                case CErrorDefine.MV_E_GC_GENERIC: errorMsg += " General error "; break;
                case CErrorDefine.MV_E_GC_ACCESS: errorMsg += " Node accessing condition error "; break;
                case CErrorDefine.MV_E_ACCESS_DENIED: errorMsg += " No permission "; break;
                case CErrorDefine.MV_E_BUSY: errorMsg += " Device is busy, or network disconnected "; break;
                case CErrorDefine.MV_E_NETER: errorMsg += " Network error "; break;
            }

            MessageBox.Show(errorMsg, "PROMPT");
        }

        /// <summary>
        /// 判断是否是黑白数据
        /// </summary>
        /// <param name="enGvspPixelType">像素格式</param>
        /// <returns>成功，返回true；错误，返回false</returns>
        private Boolean IsMonoData(MvGvspPixelType enPixelType)
        {
            switch (enPixelType)
            {
                case MvGvspPixelType.PixelType_Gvsp_Mono8:
                case MvGvspPixelType.PixelType_Gvsp_Mono8_Signed:
                case MvGvspPixelType.PixelType_Gvsp_Mono10:
                case MvGvspPixelType.PixelType_Gvsp_Mono10_Packed:
                case MvGvspPixelType.PixelType_Gvsp_Mono12:
                case MvGvspPixelType.PixelType_Gvsp_Mono12_Packed:
                case MvGvspPixelType.PixelType_Gvsp_Mono14:
                case MvGvspPixelType.PixelType_Gvsp_Mono16:
                case MvGvspPixelType.PixelType_Gvsp_HB_Mono8:
                case MvGvspPixelType.PixelType_Gvsp_HB_Mono10:
                case MvGvspPixelType.PixelType_Gvsp_HB_Mono10_Packed:
                case MvGvspPixelType.PixelType_Gvsp_HB_Mono12:
                case MvGvspPixelType.PixelType_Gvsp_HB_Mono12_Packed:
                case MvGvspPixelType.PixelType_Gvsp_HB_Mono16:
                    return true;
                default:
                    return false;
            }
        }

        /// <summary>
        /// 枚举设备
        /// </summary>
        /// <param name="sender">信号对象</param>
        /// <param name="e">参数</param>
        private void bnEnum_Click(object sender, EventArgs e)
        {
            DeviceListAcq();
        }

        /// <summary>
        /// 枚举设备函数
        /// </summary>
        private void DeviceListAcq()
        {
            // ch:创建设备列表 | en:Create Device List
            System.GC.Collect();
            cmbDeviceList.Items.Clear();
            m_ltDeviceList.Clear();
            int nRet = CSystem.EnumDevices(CSystem.MV_GIGE_DEVICE | CSystem.MV_USB_DEVICE, ref m_ltDeviceList);
            if (0 != nRet)
            {
                ShowErrorMsg("Enumerate devices fail!", nRet);
                return;
            }

            // ch:在窗体列表中显示设备名 | en:Display device name in the form list
            for (int i = 0; i < m_ltDeviceList.Count; i++)
            {
                if (CSystem.MV_GIGE_DEVICE == m_ltDeviceList[i].nTLayerType)
                {
                    CGigECameraInfo gigeInfo = (CGigECameraInfo)m_ltDeviceList[i];

                    if (gigeInfo.UserDefinedName != "")
                    {
                        cmbDeviceList.Items.Add("GEV: " + gigeInfo.UserDefinedName + " (" + gigeInfo.chSerialNumber + ")");
                    }
                    else
                    {
                        cmbDeviceList.Items.Add("GEV: " + gigeInfo.chManufacturerName + " " + gigeInfo.chModelName + " (" + gigeInfo.chSerialNumber + ")");
                    }
                }
                else if (CSystem.MV_USB_DEVICE == m_ltDeviceList[i].nTLayerType)
                {
                    CUSBCameraInfo usbInfo = (CUSBCameraInfo)m_ltDeviceList[i];
                    if (usbInfo.UserDefinedName != "")
                    {
                        cmbDeviceList.Items.Add("U3V: " + usbInfo.UserDefinedName + " (" + usbInfo.chSerialNumber + ")");
                    }
                    else
                    {
                        cmbDeviceList.Items.Add("U3V: " + usbInfo.chManufacturerName + " " + usbInfo.chModelName + " (" + usbInfo.chSerialNumber + ")");
                    }
                }
                else
                {
                    // 其他设备类型暂不支持
                }
            }

            // ch:选择第一项 | en:Select the first item
            if (0 != m_ltDeviceList.Count)
            {
                cmbDeviceList.SelectedIndex = 0;
            }
            else
            {
                ShowErrorMsg("Not Enumerated devices", 0);
            }
            return;
        }

        /// <summary>
        /// 打开设备
        /// </summary>
        /// <param name="sender">对象</param>
        /// <param name="e">参数</param>
        private void bnOpen_Click(object sender, System.EventArgs e)
        {
            if (0 == m_ltDeviceList.Count || -1 == cmbDeviceList.SelectedIndex)
            {
                ShowErrorMsg("No device, please enumerate device", 0);
                return;
            }

            // ch:获取选择的设备信息 | en:Get selected device information
            CCameraInfo device = m_ltDeviceList[cmbDeviceList.SelectedIndex];

            // ch:打开设备 | en:Open device
            if (null == m_MyCamera)
            {
                m_MyCamera = new CCamera();
                if (null == m_MyCamera)
                {
                    return;
                }
            }

            int nRet = m_MyCamera.CreateHandle(ref device);
            if (CErrorDefine.MV_OK != nRet)
            {
                ShowErrorMsg("Create device Handle fail!", nRet);
                return;
            }

            nRet = m_MyCamera.OpenDevice();
            if (CErrorDefine.MV_OK != nRet)
            {
                m_MyCamera.DestroyHandle();
                ShowErrorMsg("Device open fail!", nRet);
                return;
            }

            // ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
            if (device.nTLayerType == CSystem.MV_GIGE_DEVICE)
            {
                int nPacketSize = m_MyCamera.GIGE_GetOptimalPacketSize();
                if (0 < nPacketSize)
                {
                    nRet = m_MyCamera.SetIntValue("GevSCPSPacketSize", (uint)nPacketSize);
                    if (nRet != CErrorDefine.MV_OK)
                    {
                        ShowErrorMsg("Set Packet Size failed!", nRet);
                    }
                }
            }

            // ch:设置采集连续模式 | en:Set Continues Aquisition Mode
            m_MyCamera.SetEnumValue("AcquisitionMode", (uint)MV_CAM_ACQUISITION_MODE.MV_ACQ_MODE_CONTINUOUS);

            // ch:获取参数 | en:Get parameters
            Get_ImageCompressionMode();
            Get_PreampGain();
            Get_TriggerMode();
            Get_TriggerSelector();
            Get_TriggerSource();
            Get_PixelFormat();
            bnGetParam_Click(null, null);

            // ch:控件操作 | en:Control operation
            btnOpen.Enabled = false;
            btnClose.Enabled = true;
            btnStartGrab.Enabled = true;
            btnStopGrab.Enabled = false;
            btnTriggerExec.Enabled = false;
            btnGetParam.Enabled = true;
            btnSetParam.Enabled = true;
            cmbDeviceList.Enabled = false;
        }

        /// <summary>
        /// 获取虚拟增益模式
        /// </summary>
        private void Get_PreampGain()
        {
            cmbPreampGain.Items.Clear();
            CEnumEntry pcEnumEntry = new CEnumEntry();

            Int32 nRet = m_MyCamera.GetEnumValue("PreampGain", ref m_pcPreampGain);
            if (CErrorDefine.MV_OK == nRet)
            {
                for (UInt32 i = 0; i < m_pcPreampGain.SupportedNum; i++)
                {
                    pcEnumEntry.Value = m_pcPreampGain.SupportValue[i];
                    nRet = m_MyCamera.GetEnumEntrySymbolic("PreampGain", ref pcEnumEntry);
                    if (CErrorDefine.MV_OK == nRet)
                    {
                        cmbPreampGain.Items.Add(pcEnumEntry.Symbolic);
                    }

                    if (m_pcPreampGain.SupportValue[i] == m_pcPreampGain.CurValue)
                    {
                        cmbPreampGain.SelectedIndex = (Int32)i;
                    }
                }
                cmbPreampGain.Enabled = true;
            }
        }

        /// <summary>
        /// 获取HB模式
        /// </summary>
        private void Get_ImageCompressionMode()
        {
            cmbHBMode.Items.Clear();
            CEnumEntry pcEnumEntry = new CEnumEntry();

            Int32 nRet = m_MyCamera.GetEnumValue("ImageCompressionMode", ref m_pcImgCompressMode);
            if (CErrorDefine.MV_OK == nRet)
            {
                for (UInt32 i = 0; i < m_pcImgCompressMode.SupportedNum; i++)
                {
                    pcEnumEntry.Value = m_pcImgCompressMode.SupportValue[i];
                    nRet = m_MyCamera.GetEnumEntrySymbolic("ImageCompressionMode", ref pcEnumEntry);
                    if (CErrorDefine.MV_OK == nRet)
                    {
                        cmbHBMode.Items.Add(pcEnumEntry.Symbolic);
                    }

                    if (m_pcImgCompressMode.SupportValue[i] == m_pcImgCompressMode.CurValue)
                    {
                        cmbHBMode.SelectedIndex = (Int32)i;
                    }
                }
                cmbHBMode.Enabled = true;
            }
            else
            {
                cmbHBMode.Enabled = false;
            }
        }

        /// <summary>
        /// 获取像素格式
        /// </summary>
        private void Get_PixelFormat()
        {
            cmbPixelFormat.Items.Clear();
            CEnumEntry pcEnumEntry = new CEnumEntry();

            Int32 nRet = m_MyCamera.GetEnumValue("PixelFormat", ref m_pcPixelFormat);
            if (CErrorDefine.MV_OK == nRet)
            {
                for (UInt32 i = 0; i < m_pcPixelFormat.SupportedNum; i++)
                {
                    pcEnumEntry.Value = m_pcPixelFormat.SupportValue[i];
                    nRet = m_MyCamera.GetEnumEntrySymbolic("PixelFormat", ref pcEnumEntry);
                    if (CErrorDefine.MV_OK == nRet)
                    {
                        cmbPixelFormat.Items.Add(pcEnumEntry.Symbolic);
                    }

                    if (m_pcPixelFormat.SupportValue[i] == m_pcPixelFormat.CurValue)
                    {
                        cmbPixelFormat.SelectedIndex = (Int32)i;
                    }
                }
                cmbPixelFormat.Enabled = true;
            }
        }

        /// <summary>
        /// 获取触发选项
        /// </summary>
        private void Get_TriggerSelector()
        {
            // 获取触发选项
            cmbTriggerOpt.Items.Clear();
            CEnumEntry pcEnumEntry = new CEnumEntry();
            int nRet = m_MyCamera.GetEnumValue("TriggerSelector", ref m_pcTriggerSelector);
            if (CErrorDefine.MV_OK == nRet)
            {
                for (UInt32 i = 0; i < m_pcTriggerSelector.SupportedNum; i++)
                {
                    pcEnumEntry.Value = m_pcTriggerSelector.SupportValue[i];
                    nRet = m_MyCamera.GetEnumEntrySymbolic("TriggerSelector", ref pcEnumEntry);
                    if (CErrorDefine.MV_OK == nRet)
                    {
                        cmbTriggerOpt.Items.Add(pcEnumEntry.Symbolic);
                    }

                    if (m_pcTriggerSelector.SupportValue[i] == m_pcTriggerSelector.CurValue)
                    {
                        cmbTriggerOpt.SelectedIndex = (Int32)i;
                    }
                }
                cmbTriggerOpt.Enabled = true;
            }
        }

        /// <summary>
        /// 获取触发模式
        /// </summary>
        private void Get_TriggerMode()
        {
            // 获取触发模式
            cmbTiggerSwitch.Items.Clear();
            CEnumEntry pcEnumEntry = new CEnumEntry();
            int nRet = m_MyCamera.GetEnumValue("TriggerMode", ref m_pcTriggerMode);
            if (CErrorDefine.MV_OK == nRet)
            {
                for (UInt32 i = 0; i < m_pcTriggerMode.SupportedNum; i++)
                {
                    pcEnumEntry.Value = m_pcTriggerMode.SupportValue[i];
                    nRet = m_MyCamera.GetEnumEntrySymbolic("TriggerMode", ref pcEnumEntry);
                    if (CErrorDefine.MV_OK == nRet)
                    {
                        cmbTiggerSwitch.Items.Add(pcEnumEntry.Symbolic);
                    }

                    if (m_pcTriggerMode.SupportValue[i] == m_pcTriggerMode.CurValue)
                    {
                        cmbTiggerSwitch.SelectedIndex = (Int32)i;
                    }
                }
                cmbTiggerSwitch.Enabled = true;
            }
        }

        /// <summary>
        /// 获取触发源
        /// </summary>
        private void Get_TriggerSource()
        {
            // 获取触发源类型
            cmbTriggerSource.Items.Clear();
            CEnumEntry pcEnumEntry = new CEnumEntry();
            Int32 nRet = m_MyCamera.GetEnumValue("TriggerSource", ref m_pcTriggerSource);
            if (CErrorDefine.MV_OK == nRet)
            {
                for (UInt32 i = 0; i < m_pcTriggerSource.SupportedNum; i++)
                {
                    pcEnumEntry.Value = m_pcTriggerSource.SupportValue[i];
                    nRet = m_MyCamera.GetEnumEntrySymbolic("TriggerSource", ref pcEnumEntry);
                    if (CErrorDefine.MV_OK == nRet)
                    {
                        cmbTriggerSource.Items.Add(pcEnumEntry.Symbolic);
                    }

                    if (m_pcTriggerSource.SupportValue[i] == m_pcTriggerSource.CurValue)
                    {
                        cmbTriggerSource.SelectedIndex = (Int32)i;
                    }
                }
                cmbTriggerSource.Enabled = true;
            }
        }

        /// <summary>
        /// 关闭设备
        /// </summary>
        /// <param name="sender">对象</param>
        /// <param name="e">参数</param>
        private void bnClose_Click(object sender, System.EventArgs e)
        {
            // ch:取流标志位清零 | en:Reset flow flag bit
            if (m_bGrabbing == true)
            {
                m_bGrabbing = false;
                m_hReceiveThread.Join();
            }

            // ch:关闭设备 | en:Close Device
            m_MyCamera.CloseDevice();
            m_MyCamera.DestroyHandle();

            // ch:控件操作 | en:Control Operation
            SetCtrlWhenClose();
        }

        /// <summary>关闭设备控件操作</summary>
        private void SetCtrlWhenClose()
        {
            btnOpen.Enabled = true;
            btnClose.Enabled = false;
            btnStartGrab.Enabled = false;
            btnStopGrab.Enabled = false;
            btnTriggerExec.Enabled = false;
            cmbDeviceList.Enabled = true;

            btnSaveBmp.Enabled = false;
            btnSaveJpg.Enabled = false;
            btnSaveTiff.Enabled = false;
            btnSavePng.Enabled = false;
            tbExposure.Enabled = false;
            btnGetParam.Enabled = false;
            btnSetParam.Enabled = false;
            cmbPixelFormat.Enabled = false;
            cmbHBMode.Enabled = false;
            cmbPreampGain.Enabled = false;
            cmbTriggerSource.Enabled = false;
            cmbTriggerOpt.Enabled = false;
            cmbTiggerSwitch.Enabled = false;
            tbExposure.Enabled = false;
            tbDigitalShift.Enabled = false;
            tbAcqLineRate.Enabled = false;
            chkLineRateSwitch.Enabled = false;
        }

        /// <summary>接收线程</summary>
        public void ReceiveThreadProcess()
        {
            CFrameout pcFrameInfo = new CFrameout();
            CPixelConvertParam pcConvertParam = new CPixelConvertParam();
            CDisplayFrameInfo pcDisplayInfo = new CDisplayFrameInfo();
            int nRet = CErrorDefine.MV_OK;

            while (m_bGrabbing)
            {
                nRet = m_MyCamera.GetImageBuffer(ref pcFrameInfo, 1000);
                if (CErrorDefine.MV_OK == nRet)
                {
                    // 保存图像数据用于保存图像文件
                    lock (BufForDriverLock)
                    {
                        m_pcImgForDriver = pcFrameInfo.Image.Clone() as CImage;
                        m_pcImgSpecInfo = pcFrameInfo.FrameSpec;

                        pcConvertParam.InImage = pcFrameInfo.Image;
                        if (PixelFormat.Format8bppIndexed == m_pcBitmap.PixelFormat)
                        {
                            pcConvertParam.OutImage.PixelType = MvGvspPixelType.PixelType_Gvsp_Mono8;
                            m_MyCamera.ConvertPixelType(ref pcConvertParam);
                        }
                        else
                        {
                            pcConvertParam.OutImage.PixelType = MvGvspPixelType.PixelType_Gvsp_BGR8_Packed;
                            m_MyCamera.ConvertPixelType(ref pcConvertParam);
                        }

                        // ch:保存Bitmap数据 | en:Save Bitmap Data
                        BitmapData m_pcBitmapData = m_pcBitmap.LockBits(new Rectangle(0, 0, pcConvertParam.InImage.Width, pcConvertParam.InImage.Height), ImageLockMode.ReadWrite, m_pcBitmap.PixelFormat);
                        Marshal.Copy(pcConvertParam.OutImage.ImageData, 0, m_pcBitmapData.Scan0, (Int32)pcConvertParam.OutImage.ImageData.Length);
                        m_pcBitmap.UnlockBits(m_pcBitmapData);
                    }

                    // 渲染图像数据
                    pcDisplayInfo.WindowHandle = pictureBox1.Handle;
                    pcDisplayInfo.Image = pcFrameInfo.Image;
                    m_MyCamera.DisplayOneFrame(ref pcDisplayInfo);

                    m_MyCamera.FreeImageBuffer(ref pcFrameInfo);
                }
                else
                {
                    if (MV_CAM_TRIGGER_MODE.MV_TRIGGER_MODE_ON == m_enTriggerMode)
                    {
                        Thread.Sleep(5);
                    }
                }
            }
        }

        /// <summary>
        /// 取图前的必要操作步骤
        /// </summary>
        /// <returns></returns>
        private Int32 NecessaryOperBeforeGrab()
        {
            // ch:取图像宽 | en:Get Iamge Width
            CIntValue pcWidth = new CIntValue();
            int nRet = m_MyCamera.GetIntValue("WidthMax", ref pcWidth);
            if (CErrorDefine.MV_OK != nRet)
            {
                ShowErrorMsg("Get Width Info Fail!", nRet);
                return nRet;
            }

            // ch:取图像高 | en:Get Iamge Height
            CIntValue pcHeight = new CIntValue();
            nRet = m_MyCamera.GetIntValue("WidthMax", ref pcHeight);
            if (CErrorDefine.MV_OK != nRet)
            {
                ShowErrorMsg("Get Height Info Fail!", nRet);
                return nRet;
            }
            // ch:取像素格式 | en:Get Pixel Format
            CEnumValue m_pcPixelFormat = new CEnumValue();
            nRet = m_MyCamera.GetEnumValue("PixelFormat", ref m_pcPixelFormat);
            if (CErrorDefine.MV_OK != nRet)
            {
                ShowErrorMsg("Get Pixel Format Fail!", nRet);
                return nRet;
            }

            // ch:设置bitmap像素格式
            if ((Int32)MvGvspPixelType.PixelType_Gvsp_Undefined == (Int32)m_pcPixelFormat.CurValue)
            {
                ShowErrorMsg("Unknown Pixel Format!", CErrorDefine.MV_E_UNKNOW);
                return CErrorDefine.MV_E_UNKNOW;
            }
            else if (IsMonoData((MvGvspPixelType)m_pcPixelFormat.CurValue))
            {
                m_enBitmapPixelFormat = PixelFormat.Format8bppIndexed;
            }
            else
            {
                m_enBitmapPixelFormat = PixelFormat.Format24bppRgb;
            }

            if (null != m_pcBitmap)
            {
                m_pcBitmap.Dispose();
                m_pcBitmap = null;
            }
            m_pcBitmap = new Bitmap((Int32)pcWidth.CurValue, (Int32)pcHeight.CurValue, m_enBitmapPixelFormat);

            // ch:Mono8格式，设置为标准调色板 | en:Set Standard Palette in Mono8 Format
            if (PixelFormat.Format8bppIndexed == m_enBitmapPixelFormat)
            {
                ColorPalette palette = m_pcBitmap.Palette;
                for (int i = 0; i < palette.Entries.Length; i++)
                {
                    palette.Entries[i] = Color.FromArgb(i, i, i);
                }
                m_pcBitmap.Palette = palette;
            }

            return CErrorDefine.MV_OK;
        }

        /// <summary>
        /// 开始采集
        /// </summary>
        /// <param name="sender">对象</param>
        /// <param name="e">参数</param>
        private void bnStartGrab_Click(object sender, System.EventArgs e)
        {
            // ch:前置配置 | en:pre-operation
            int nRet = NecessaryOperBeforeGrab();
            if (CErrorDefine.MV_OK != nRet)
            {
                return;
            }

            // ch:标志位置位true | en:Set position bit true
            m_bGrabbing = true;

            m_hReceiveThread = new Thread(ReceiveThreadProcess);
            m_hReceiveThread.Start();

            // ch:开始采集 | en:Start Grabbing
            nRet = m_MyCamera.StartGrabbing();
            if (CErrorDefine.MV_OK != nRet)
            {
                m_bGrabbing = false;
                m_hReceiveThread.Join();
                ShowErrorMsg("Start Grabbing Fail!", nRet);
                return;
            }

            // ch:控件操作 | en:Control Operation
            SetCtrlWhenStartGrab();
        }

        /// <summary>
        /// 开始采集控件操作
        /// </summary>
        private void SetCtrlWhenStartGrab()
        {
            btnStartGrab.Enabled = false;
            btnStopGrab.Enabled = true;

            if ((MV_CAM_TRIGGER_MODE.MV_TRIGGER_MODE_ON == m_enTriggerMode) 
                && (MV_CAM_TRIGGER_SOURCE.MV_TRIGGER_SOURCE_SOFTWARE == m_enTriggerSource) && m_bGrabbing)
            {
                btnTriggerExec.Enabled = true;
            }

            btnSaveBmp.Enabled = true;
            btnSaveJpg.Enabled = true;
            btnSaveTiff.Enabled = true;
            btnSavePng.Enabled = true;
            cmbPixelFormat.Enabled = false;
            cmbHBMode.Enabled = false;
        }

        /// <summary>
        /// 软触发执行一次
        /// </summary>
        /// <param name="sender">对象</param>
        /// <param name="e">参数</param>
        private void bnTriggerExec_Click(object sender, System.EventArgs e)
        {
            // ch:触发命令 | en:Trigger command
            int nRet = m_MyCamera.SetCommandValue("TriggerSoftware");
            if (CErrorDefine.MV_OK != nRet)
            {
                ShowErrorMsg("Trigger Software Fail!", nRet);
            }
        }

        /// <summary>
        /// 停止采集
        /// </summary>
        /// <param name="sender">对象</param>
        /// <param name="e">参数</param>
        private void bnStopGrab_Click(object sender, System.EventArgs e)
        {
            // ch:标志位设为false | en:Set flag bit false
            m_bGrabbing = false;
            m_hReceiveThread.Join();

            // ch:停止采集 | en:Stop Grabbing
            int nRet = m_MyCamera.StopGrabbing();
            if (nRet != CErrorDefine.MV_OK)
            {
                ShowErrorMsg("Stop Grabbing Fail!", nRet);
            }

            // ch:控件操作 | en:Control Operation
            SetCtrlWhenStopGrab();
        }

        /// <summary>停止采集控件操作</summary>
        private void SetCtrlWhenStopGrab()
        {
            btnStartGrab.Enabled = true;
            btnStopGrab.Enabled = false;
            btnTriggerExec.Enabled = false;
            btnSaveBmp.Enabled = false;
            btnSaveJpg.Enabled = false;
            btnSaveTiff.Enabled = false;
            btnSavePng.Enabled = false;
            cmbPixelFormat.Enabled = true;
            cmbHBMode.Enabled = true;
        }

        /// <summary>
        /// 保存Bmp文件
        /// </summary>
        /// <param name="sender">对象</param>
        /// <param name="e">参数</param>
        private void bnSaveBmp_Click(object sender, System.EventArgs e)
        {
            if (false == m_bGrabbing)
            {
                ShowErrorMsg("Not Start Grabbing", 0);
                return;
            }

            CSaveImgToFileParam stSaveFileParam = new CSaveImgToFileParam();

            lock (BufForDriverLock)
            {
                if (m_pcImgForDriver.FrameLen == 0)
                {
                    ShowErrorMsg("Save Bmp Fail!", 0);
                    return;
                }
                stSaveFileParam.ImageType = MV_SAVE_IAMGE_TYPE.MV_IMAGE_BMP;
                stSaveFileParam.Image = m_pcImgForDriver;
                stSaveFileParam.MethodValue = 2;
                stSaveFileParam.ImagePath = "Image_w" + stSaveFileParam.Image.Width.ToString() + "_h" + stSaveFileParam.Image.Height.ToString() + "_fn" + m_pcImgSpecInfo.FrameNum.ToString() + ".bmp";
                int nRet = m_MyCamera.SaveImageToFile(ref stSaveFileParam);
                if (CErrorDefine.MV_OK != nRet)
                {
                    ShowErrorMsg("Save Bmp Fail!", nRet);
                    return;
                }
            }

            ShowErrorMsg("Save Succeed!", 0);
        }

        /// <summary>
        /// 保存JPG文件
        /// </summary>
        /// <param name="sender">对象</param>
        /// <param name="e">参数</param>
        private void bnSaveJpg_Click(object sender, System.EventArgs e)
        {
            if (false == m_bGrabbing)
            {
                ShowErrorMsg("Not Start Grabbing", 0);
                return;
            }

            CSaveImgToFileParam stSaveFileParam = new CSaveImgToFileParam();
            lock (BufForDriverLock)
            {
                if (m_pcImgForDriver.FrameLen == 0)
                {
                    ShowErrorMsg("Save Jpeg Fail!", 0);
                    return;
                }
                stSaveFileParam.ImageType = MV_SAVE_IAMGE_TYPE.MV_IMAGE_JPEG;
                stSaveFileParam.Image = m_pcImgForDriver;
                stSaveFileParam.Quality = 80;
                stSaveFileParam.MethodValue = 2;
                stSaveFileParam.ImagePath = "Image_w" + stSaveFileParam.Image.Width.ToString() + "_h" + stSaveFileParam.Image.Height.ToString() + "_fn" + m_pcImgSpecInfo.FrameNum.ToString() + ".jpg";
                int nRet = m_MyCamera.SaveImageToFile(ref stSaveFileParam);
                if (CErrorDefine.MV_OK != nRet)
                {
                    ShowErrorMsg("Save Jpeg Fail!", nRet);
                    return;
                }
            }

            ShowErrorMsg("Save Succeed!", 0);
        }

        /// <summary>
        /// 保存Tiff格式文件
        /// </summary>
        /// <param name="sender">对象</param>
        /// <param name="e">参数</param>
        private void bnSaveTiff_Click(object sender, System.EventArgs e)
        {
            if (false == m_bGrabbing)
            {
                ShowErrorMsg("Not Start Grabbing", 0);
                return;
            }

            CSaveImgToFileParam stSaveFileParam = new CSaveImgToFileParam();

            lock (BufForDriverLock)
            {
                if (m_pcImgForDriver.FrameLen == 0)
                {
                    ShowErrorMsg("Save Tiff Fail!", 0);
                    return;
                }
                stSaveFileParam.ImageType = MV_SAVE_IAMGE_TYPE.MV_IMAGE_TIF;
                stSaveFileParam.Image = m_pcImgForDriver;
                stSaveFileParam.MethodValue = 2;
                stSaveFileParam.ImagePath = "Image_w" + stSaveFileParam.Image.Width.ToString() + "_h" + stSaveFileParam.Image.Height.ToString() + "_fn" + m_pcImgSpecInfo.FrameNum.ToString() + ".tif";
                int nRet = m_MyCamera.SaveImageToFile(ref stSaveFileParam);
                if (CErrorDefine.MV_OK != nRet)
                {
                    ShowErrorMsg("Save Tiff Fail!", nRet);
                    return;
                }
            }

            ShowErrorMsg("Save Succeed!", 0);
        }

        /// <summary>
        /// 保存PNG格式文件
        /// </summary>
        /// <param name="sender">文件</param>
        /// <param name="e">参数</param>
        private void bnSavePng_Click(object sender, System.EventArgs e)
        {
            if (false == m_bGrabbing)
            {
                ShowErrorMsg("Not Start Grabbing", 0);
                return;
            }

            CSaveImgToFileParam stSaveFileParam = new CSaveImgToFileParam();
            lock (BufForDriverLock)
            {
                if (m_pcImgForDriver.FrameLen == 0)
                {
                    ShowErrorMsg("Save Png Fail!", 0);
                    return;
                }
                stSaveFileParam.ImageType = MV_SAVE_IAMGE_TYPE.MV_IMAGE_PNG;
                stSaveFileParam.Image = m_pcImgForDriver;
                stSaveFileParam.Quality = 8;
                stSaveFileParam.MethodValue = 2;
                stSaveFileParam.ImagePath = "Image_w" + stSaveFileParam.Image.Width.ToString() + "_h" + stSaveFileParam.Image.Height.ToString() + "_fn" + m_pcImgSpecInfo.FrameNum.ToString() + ".png";
                int nRet = m_MyCamera.SaveImageToFile(ref stSaveFileParam);
                if (CErrorDefine.MV_OK != nRet)
                {
                    ShowErrorMsg("Save Png Fail!", nRet);
                    return;
                }
            }

            ShowErrorMsg("Save Succeed!", 0);
        }

        /// <summary>
        /// 设置参数
        /// </summary>
        /// <param name="sender">对象</param>
        /// <param name="e">参数</param>
        private void bnSetParam_Click(object sender, System.EventArgs e)
        {
            int nRet = CErrorDefine.MV_OK;

            // 设置曝光
            if (tbExposure.Enabled)
            {
                try
                {
                    float.Parse(tbExposure.Text);
                    m_MyCamera.SetEnumValue("ExposureAuto", 0);
                    nRet = m_MyCamera.SetFloatValue("ExposureTime", float.Parse(tbExposure.Text));
                    if (CErrorDefine.MV_OK != nRet)
                    {
                        ShowErrorMsg("Set Exposure Time Fail!", nRet);
                    }
                }
                catch
                {
                    ShowErrorMsg("Please enter ExposureTime correct", 0);
                }
            }

            // 设置数字增益
            if (tbDigitalShift.Enabled)
            {
                try
                {
                    float.Parse(tbDigitalShift.Text);
                    m_MyCamera.SetBoolValue("DigitalShiftEnable", true);
                    nRet = m_MyCamera.SetFloatValue("DigitalShift", float.Parse(tbDigitalShift.Text));
                    if (CErrorDefine.MV_OK != nRet)
                    {
                        ShowErrorMsg("Set Digital Shift Fail!", nRet);
                    }
                }
                catch
                {
                    ShowErrorMsg("Please enter DigitalShift correct", 0);
                }
            }
            
            // 设置行频设定值
            if (tbAcqLineRate.Enabled)
            {
                try
                {
                    int.Parse(tbAcqLineRate.Text);
                    nRet = m_MyCamera.SetIntValue("AcquisitionLineRate", int.Parse(tbAcqLineRate.Text));
                    if (CErrorDefine.MV_OK != nRet)
                    {
                        ShowErrorMsg("Set Acquisition Line Rate Fail!", nRet);
                    }
                }
                catch
                {
                    ShowErrorMsg("Please enter AcquisitionLineRate correct", 0);
                }
            }
        }

        /// <summary>
        /// 获取参数
        /// </summary>
        /// <param name="sender">对象</param>
        /// <param name="e">参数</param>
        private void bnGetParam_Click(object sender, System.EventArgs e)
        {
            // 获取曝光参数
            CFloatValue pcExposureTime = new CFloatValue();
            Int32 nRet = m_MyCamera.GetFloatValue("ExposureTime", ref pcExposureTime);
            if (CErrorDefine.MV_OK == nRet)
            {
                tbExposure.Text = pcExposureTime.CurValue.ToString("F2");
                tbExposure.Enabled = true;
            }

            // 获取数字增益参数
            CFloatValue pcDigitalShift = new CFloatValue();
            nRet = m_MyCamera.GetFloatValue("DigitalShift", ref pcDigitalShift);
            if (CErrorDefine.MV_OK == nRet)
            {
                tbDigitalShift.Text = pcDigitalShift.CurValue.ToString("F2");
                tbDigitalShift.Enabled = true;
            }

            // 获取行频使能开关
            bool bAcqLineRateEnable = false;
            nRet = m_MyCamera.GetBoolValue("AcquisitionLineRateEnable", ref bAcqLineRateEnable);
            if (CErrorDefine.MV_OK == nRet)
            {
                chkLineRateSwitch.Enabled = true;
                chkLineRateSwitch.Checked = bAcqLineRateEnable;
            }

            // 获取行频设置值
            CIntValue pcAcqLineRate = new CIntValue();
            nRet = m_MyCamera.GetIntValue("AcquisitionLineRate", ref pcAcqLineRate);
            if (CErrorDefine.MV_OK == nRet)
            {
                tbAcqLineRate.Text = pcAcqLineRate.CurValue.ToString();
                tbAcqLineRate.Enabled = true;
            }

            // 获取行频实际值
            CIntValue pcResLineRate = new CIntValue();
            nRet = m_MyCamera.GetIntValue("ResultingLineRate", ref pcResLineRate);
            if (CErrorDefine.MV_OK == nRet)
            {
                tbResLineRate.Text = pcResLineRate.CurValue.ToString();
                tbResLineRate.Enabled = true;
            }
        }

        /// <summary>
        /// 设置触发选项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbTriggerOpt_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 设置触发选项
            int nRet = m_MyCamera.SetEnumValue("TriggerSelector", m_pcTriggerSelector.SupportValue[cmbTriggerOpt.SelectedIndex]);
            if (CErrorDefine.MV_OK != nRet)
            {
                ShowErrorMsg("set Trigger Selector Failed", nRet);
                for (UInt32 i = 0; i < m_pcTriggerSelector.SupportedNum; i++)
                {
                    if (m_pcTriggerSelector.SupportValue[i] == m_pcTriggerSelector.CurValue)
                    {
                        cmbTriggerOpt.SelectedIndex = (Int32)i;
                        return;
                    }
                }
            }
            m_pcTriggerSelector.CurValue = m_pcTriggerSelector.SupportValue[cmbTriggerOpt.SelectedIndex];
        }

        /// <summary>
        /// 设置触发模式
        /// </summary>
        /// <param name="sender">对象</param>
        /// <param name="e">参数</param>
        private void cbTiggerSwitch_SelectedIndexChanged(object sender, EventArgs e)
        {
            int nRet = m_MyCamera.SetEnumValue("TriggerMode", (uint)m_pcTriggerMode.SupportValue[cmbTiggerSwitch.SelectedIndex]);
            if (CErrorDefine.MV_OK != nRet)
            {
                ShowErrorMsg("set Trigger Mode Failed", nRet);
                for (UInt32 i = 0; i < m_pcTriggerMode.SupportedNum; i++)
                {
                    if (m_pcTriggerMode.SupportValue[i] == m_pcTriggerMode.CurValue)
                    {
                        cmbTiggerSwitch.SelectedIndex = (Int32)i;
                        return;
                    }
                }
            }
            m_pcTriggerMode.CurValue = m_pcTriggerMode.SupportValue[cmbTiggerSwitch.SelectedIndex];
            m_enTriggerMode = (MV_CAM_TRIGGER_MODE)m_pcTriggerMode.CurValue;

            if ((MV_CAM_TRIGGER_MODE.MV_TRIGGER_MODE_ON == m_enTriggerMode)
                && (MV_CAM_TRIGGER_SOURCE.MV_TRIGGER_SOURCE_SOFTWARE == m_enTriggerSource) && m_bGrabbing)
            {
                btnTriggerExec.Enabled = true;
            }
            else
            {
                btnTriggerExec.Enabled = false;
            }
        }

        /// <summary>
        /// 设置触发源
        /// </summary>
        /// <param name="sender">对象</param>
        /// <param name="e">参数</param>
        private void cmbTriggerSource_SelectedIndexChanged(object sender, EventArgs e)
        {
            uint nCurent = m_pcTriggerSource.SupportValue[cmbTriggerSource.SelectedIndex];
            int nRet = m_MyCamera.SetEnumValue("TriggerSource", nCurent);
            if (CErrorDefine.MV_OK != nRet)
            {
                ShowErrorMsg("set Trigger Source Failed", nRet);
                for (UInt32 i = 0; i < m_pcTriggerSource.SupportedNum; i++)
                {
                    if (m_pcTriggerSource.SupportValue[i] == m_pcTriggerSource.CurValue)
                    {
                        cmbTriggerSource.SelectedIndex = (Int32)i;
                        return;
                    }
                }
            }
            m_pcTriggerSource.CurValue = m_pcTriggerSource.SupportValue[cmbTriggerSource.SelectedIndex];
            m_enTriggerSource = (MV_CAM_TRIGGER_SOURCE)m_pcTriggerSource.CurValue;

            if ((MV_CAM_TRIGGER_MODE.MV_TRIGGER_MODE_ON == m_enTriggerMode)
                && (MV_CAM_TRIGGER_SOURCE.MV_TRIGGER_SOURCE_SOFTWARE == m_enTriggerSource) && m_bGrabbing)
            {
                btnTriggerExec.Enabled = true;
            }
            else
            {
                btnTriggerExec.Enabled = false;
            }
        }

        /// <summary>
        /// 设置像素格式
        /// </summary>
        /// <param name="sender">对象</param>
        /// <param name="e">参数</param>
        private void cbPixelFormat_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 设置像素格式
            int nRet = m_MyCamera.SetEnumValue("PixelFormat", m_pcPixelFormat.SupportValue[cmbPixelFormat.SelectedIndex]);
            if (nRet != CErrorDefine.MV_OK)
            {
                ShowErrorMsg("Set PixelFormat Fail!", nRet);
                for (UInt32 i = 0; i < m_pcPixelFormat.SupportedNum; i++)
                {
                    if (m_pcPixelFormat.SupportValue[i] == m_pcPixelFormat.CurValue)
                    {
                        cmbPixelFormat.SelectedIndex = (Int32)i;
                        return;
                    }
                }
            }
            m_pcPixelFormat.CurValue = m_pcPixelFormat.SupportValue[cmbPixelFormat.SelectedIndex];
            Get_ImageCompressionMode();
        }

        /// <summary>
        /// 设置HB无损压缩模式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbHBMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            Int32 nRet = m_MyCamera.SetEnumValue("ImageCompressionMode", m_pcImgCompressMode.SupportValue[cmbHBMode.SelectedIndex]);
            if (nRet != CErrorDefine.MV_OK)
            {
                ShowErrorMsg("Set PixelFormat Fail!", nRet);
                for (UInt32 i = 0; i < m_pcImgCompressMode.SupportedNum; i++)
                {
                    if (m_pcImgCompressMode.SupportValue[i] == m_pcImgCompressMode.CurValue)
                    {
                        cmbHBMode.SelectedIndex = (Int32)i;
                        return;
                    }
                }
            }
            m_pcImgCompressMode.CurValue = m_pcImgCompressMode.SupportValue[cmbHBMode.SelectedIndex];
        }

        /// <summary>
        /// 设置模拟增益
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbPreampGain_SelectedIndexChanged(object sender, EventArgs e)
        {
            Int32 nRet = m_MyCamera.SetEnumValue("PreampGain", m_pcPreampGain.SupportValue[cmbPreampGain.SelectedIndex]);
            if (CErrorDefine.MV_OK != nRet)
            {
                ShowErrorMsg("Set PreampGain Fail!", nRet);
                for (UInt32 i = 0; i < m_pcPreampGain.SupportedNum; i++)
                {
                    if (m_pcPreampGain.SupportValue[i] == m_pcPreampGain.CurValue)
                    {
                        cmbPreampGain.SelectedIndex = (Int32)i;
                        return;
                    }
                }
            }
            m_pcPreampGain.CurValue = m_pcPreampGain.SupportValue[cmbPreampGain.SelectedIndex];
        }

        /// <summary>
        /// 采集行频使能控制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkLineRateSwitch_CheckedChanged(object sender, EventArgs e)
        {
            if (chkLineRateSwitch.Checked)
            {
                m_MyCamera.SetBoolValue("AcquisitionLineRateEnable", true);
            }
            else
            {
                m_MyCamera.SetBoolValue("AcquisitionLineRateEnable", false);
            }
        }

        /// <summary>
        /// 窗口关闭
        /// </summary>
        /// <param name="sender">对象</param>
        /// <param name="e">参数</param>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            bnClose_Click(sender, e);
        }
    }
}
